import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../store";
import { message as antdMessage } from "antd";
import { RouteRawState } from "../types";
import { useLocation, Navigate } from "react-router-dom";
import React, { useEffect } from "react";
import { getUserInfo } from "../service";
import {
  LoginQuitActionCreator,
  loginSuccessActionCreator,
} from "../store/user/userActions";

type PropsType = {
  route: RouteRawState;
};

// 全局拦截
const BeforeEachRoute: React.FC<PropsType> = ({ route }) => {
  // 路由进入前， 可以先做点事情
  // 路由拦截 导航守卫
  // 白名单： 不需要 token 就可以进入
  const whiteList = ["/signin"];

  // 1. 设置title
  document.title = route.meta.title;

  // 2. 做个拦截
  const token = useSelector((state: RootState) => state.user.token);
  const role = useSelector((state: RootState) => state.user.role);
  const dispatch = useDispatch();
  const { pathname } = useLocation();

  if (token) {
    // 2-1 已登录状态
    if (token && !role) {
      // 验证 token
      (async () => {
        const resp = await getUserInfo(token);
        const { code, data } = resp.data;
        if (code === 200) {
          dispatch(
            loginSuccessActionCreator({
              ...data,
              token,
            })
          );
        } else {
          dispatch(LoginQuitActionCreator());
        }
      })();
    }

    // 2-1-1 进入白名单页面
    if (whiteList.includes(pathname)) {
      return <Navigate to="/"></Navigate>;
    } else {
      // 2-1-1 进入非白名单页面
      return <>{route.element}</>;
    }
  } else {
    // 2-2 未登录状态
    // 2-2-1 进入的是白名单 不要求登录
    if (whiteList.includes(pathname)) {
      return <>{route.element}</>;
    } else {
      // 2-2-2 进入的非白名单 要求登录
      antdMessage.warning("用户未登录, 请登录 !!!");
      return <Navigate to="/signin"></Navigate>;
    }
  }
};

export default BeforeEachRoute;
